import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程安全demo 使用lock解决线程安全问题 ReentrantLock
 *
 * @author brianxia
 * @version 1.0
 * @date 2021/12/9 16:37
 */
public class ThreadSafeDemo2 {

    public static volatile int count = 0;
    public static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {


        //1.创建两个线程
        Thread thread = new Thread(() -> {
            try {
                lock.lock();
                for (int i = 0; i < 10000; i++) {
                    count++;
                }
            } finally {
                lock.unlock();
            }

        });

        //2.分别对count ++
        Thread thread2 = new Thread(() -> {
            try {
                lock.lock();
                for (int i = 0; i < 10000; i++) {
                    count++;
                }
            } finally {
                lock.unlock();
            }

        });

        thread.start();
        thread2.start();
        //3.打印结果
        thread.join();
        thread2.join();
        System.out.println(count);
    }

}
